package com.cysion.study.ui.personal

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Intent
import android.graphics.Bitmap
import android.os.StrictMode
import android.text.InputType
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.entity.AddressBean
import com.cysion.study.entity.AddressInfoPO
import com.cysion.study.entity.UserEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.widget.BitmapUtil
import com.cysion.study.widget.FileUtils
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import com.winfo.photoselector.PhotoSelector
import kotlinx.android.synthetic.main.activity_personal.*
import org.json.JSONObject
import java.io.*
import java.util.*

//个人信息  使用中
class PersonalInfoActivity : BaseActivity(), View.OnClickListener {


    var userInfo: UserEntity? = null
    override fun getLayoutId(): Int = R.layout.activity_personal

    override fun initView() {
        initPhotoError()

        darkTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("个人资料")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }


        iv_head.setOnClickListener(this)
        tv_name.setOnClickListener(this)
        tv_brithday.setOnClickListener(this)
        tv_area.setOnClickListener(this)
        tv_address.setOnClickListener(this)
        tv_sex.setOnClickListener(this)
        iv_bg.setOnClickListener(this)

        //获取日历的一个对象
        cal = Calendar.getInstance()
        //获取年月日时分秒的信息
        year = cal.get(Calendar.YEAR)
        //month从0开始计算(一月month = 0)
        month = cal.get(Calendar.MONTH) + 1
        day = cal.get(Calendar.DAY_OF_MONTH)
        hour = cal.get(Calendar.HOUR_OF_DAY)
        minute = cal.get(Calendar.MINUTE)
    }

    private fun initPhotoError() {
        // android 7.0系统解决拍照的问题
        var builder =  StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }


    override fun initData() {
        super.initData()
        getUserInfo()
//        loadProviceData()
    }

    private fun loadProviceData() {
        Alert.loading(self)
        ApiClient.api.getAllCity(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    pcaCodeList = it
                    //条件选择器
                    initAddressPicker(pcaCodeList)
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private var userBean: UserEntity? = null

    private fun getUserInfo() {
        Alert.loading(self)
        ApiClient.api.getUserInfos(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    userBean = it
                    UserCache.save(it)
                    if (self!=null) {
                        initUser()
                    }
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun initUser() {
        userInfo = UserCache.userInfo
        /*{"status":"SUCCESS","msg":"","data":{"birthday":"","address":"","city":"","nickName":"18628178473"
            ,"headImageUrl":"","sex":0,"type":0,"isHasPayPassword":1,"province":"","money":388.00
            ,"phone":"18628178473","id":1,"backImageUrl":""},"code":0,"count":0}*/
        /*Glide.with(context).load(UserCache.userInfo?.avatar ?: R.mipmap.default_head)
            .apply(RequestOptions.circleCropTransform())
            .into(iv_head)*/
        Glide.with(self).load(UserCache.userInfo?.headImageUrl).apply(
            RequestOptions().placeholder(R.mipmap.default_head)
        ).into(iv_head)
        /*Glide.with(iv_head.context).load(UserCache.userInfo?.backImageUrl).apply(
            RequestOptions().placeholder(R.mipmap.default_head)
        ).into(iv_bg)*/
        tv_name.text = UserCache.userInfo?.nickName
        //性别 0.未知 1.男 2.女
        if (UserCache.userInfo?.sex == 0) {
            tv_sex.text = "未知"
        } else if (UserCache.userInfo?.sex == 1) {
            tv_sex.text = "男"
        } else if (UserCache.userInfo?.sex == 2) {
            tv_sex.text = "女"
        }
        if (TextUtils.isEmpty(UserCache.userInfo?.birthday)) {
            tv_brithday.text = "请选择出生日期"
        } else {
            tv_brithday.text = UserCache.userInfo?.birthday
        }

        if (TextUtils.isEmpty(UserCache.userInfo?.address)) {
            tv_address.text = "请填写详细地址"
        } else {
            tv_address.text = UserCache.userInfo?.address
        }

        if (TextUtils.isEmpty(UserCache.userInfo?.city)) {
            tv_area.text = "请选择城市"
        } else {
            tv_area.text = UserCache.userInfo?.province + UserCache.userInfo?.city

        }


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 103&&resultCode== Activity.RESULT_OK) {
            var localPics = ArrayList<String>()
            localPics.clear()
//            localPics.addAll(data?.getStringArrayListExtra(PhotoSelector.SELECT_RESULT) as ArrayList<String>)
            var lPics = ArrayList<String>()
            lPics.clear()
            lPics = data?.getStringArrayListExtra(PhotoSelector.SELECT_RESULT) as ArrayList<String>
            println("###选择返回="+lPics.size)
            var protraitPath = ""
            if (lPics.size > 0) {
                for (pic in lPics) {
                    protraitPath = compressImage(pic)
                    localPics.add(protraitPath)
                }
            }
            showWaitDialog("上传中...",false)
            for (obj in localPics) {
                println("###图片返回="+obj)
                uploadPic(File(obj))
            }
        }
    }

    fun compressImage(picFileName: String): String {
        val bitmap = BitmapUtil.decodeFile(picFileName, 960)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 90f
        while (baos.toByteArray().size / 1024 > 200 && options > 80) { // 循环判断如果压缩后图片
            baos.reset()// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options.toInt(), baos)// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5f// 每次都减少10
        }
        val file = FileUtils.createFileWithSuffix(".jpg", this)
        println("压缩后大小 " + baos.toByteArray().size / 1024 + "==options=" + options)
        // 保存新文件
        try {
            val out = FileOutputStream(file)
            out.write(baos.toByteArray())
            out.flush()
            out.close()
            return file.getAbsolutePath()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return ""
        } catch (e: IOException) {
            e.printStackTrace()
            return ""
        }
    }
    private var isHead: Boolean = true

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_head -> {
                isHead = true
//                takePhoto()
                //单选
                PhotoSelector.builder().setSingle(true).start(this, 103)
            }
            R.id.iv_bg -> {
                isHead = false
//                takePhoto()
            }
            R.id.tv_name -> {
                editContent(tv_name.text.toString())
            }
            R.id.tv_sex->{
                Alert.selectSex(this, "", "", "", "确定") { confirm, type ->
                    if (TextUtils.isEmpty(type)) {
                        ShowToast("请选择性别")
                        return@selectSex
                    }

                    if (confirm == CONFIRM) {
                        Alert.close()
                        //type=1男  =2女
                        if (type == "1") {
                            sex = "1"
                            tv_sex.text = "男"
                        } else if (type == "2") {
                            sex = "2"
                            tv_sex.text = "女"
                        }
                        userInfo?.sex = sex.toInt()
                        UserCache.save(userInfo)
                        updateUser()
                    }
                }
            }
            R.id.tv_brithday->{
                dialog()
            }
            R.id.tv_area->{//修改省市
                loadProviceData()

            }
            R.id.tv_address -> {
                editAddress()
            }
        }
    }


    private fun uploadPic(headUrl: File) {
        val params = RequestParams()
        params.put("file", headUrl)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        var url=Urls.uploadPicture

        println("上传头像=="+url+"参数="+params.toString())
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)

                try {
                    if (response?.getString("code") == "0") {
                        hideWaitDialog()
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        if (isHead) {
                            userBean?.headImageUrl = response.getString("data")
                        } else {
                            userBean?.backImageUrl = response.getString("data")
                        }
                        updateUser()
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    hideWaitDialog()
                } finally {

                    hideWaitDialog()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                println("####上传失败"+statusCode+"##="+responseString)
                hideWaitDialog()
            }
        })
    }





    private fun editAddress() {
        val view = Alert.setup(this, R.layout.dialog_comment, 0.8f, false, null)
        val tv_title = view.findViewById<TextView>(R.id.tv_title)
        tv_title.text = "地址"
        val editor = view.findViewById<TextView>(R.id.etComment)
        editor.hint = "请输入详细地址"
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            Alert.close()
//            clickListener?.invoke(CANCEL, "")
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (TextUtils.isEmpty(editor.text.toString().trim())) {
                ShowToast("请输入内容")
                return@setOnClickListener
            }
            Alert.close()
//            clickListener?.invoke(CONFIRM, editor.text.toString().trim())
            userInfo?.address = editor.text.toString().trim()
            UserCache.save(userInfo)
            updateUser()
        }
    }
    private var sex = ""
    private lateinit var pcaCodeList: List<AddressBean>


    private fun editContent(name: String) {
        val view = Alert.setup(this, R.layout.dialog_comment, 0.8f, false, null)
        val tv_title = view.findViewById<TextView>(R.id.tv_title)
        tv_title.text = "昵称"
        val editor = view.findViewById<EditText>(R.id.etComment)
        editor.inputType=InputType.TYPE_CLASS_TEXT
        editor.setText(name)
        editor.setSelection(name.length)
        editor.setFocusable(true);
        editor.setFocusableInTouchMode(true);
        editor.requestFocus()
//        editor.inputType= InputType.TYPE_CLASS_TEXT
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            Alert.close()
//            clickListener?.invoke(CANCEL, "")
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (TextUtils.isEmpty(editor.text.toString().trim())) {
                ShowToast("请输入内容")
                return@setOnClickListener
            }
            if (editor.text.toString().trim().length > 10) {
                ShowToast("请输入2-10个字符")
                return@setOnClickListener
            }
            if (editor.text.toString().trim().length < 2) {
                ShowToast("请输入2-10个字符")
                return@setOnClickListener
            }
            Alert.close()
//            clickListener?.invoke(CONFIRM, editor.text.toString().trim())
            userInfo?.nickName = editor.text.toString().trim()
            UserCache.save(userInfo)
            updateUser()
        }
    }

    private fun updateUser() {
        Alert.loading(self)
        ApiClient.api.setInfo(
            UserCache.token,
            UserCache.userInfo!!.nickName,
            UserCache.userInfo!!.backImageUrl,
            UserCache.userInfo!!.headImageUrl,
            UserCache.userInfo!!.birthday,
            UserCache.userInfo!!.city,
            UserCache.userInfo!!.province,
            UserCache.userInfo!!.address,
            UserCache.userInfo!!.sex.toString()
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    getUserInfo()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    // * 初始化地址数据
    private fun initAddressPicker(pcaCodeList: List<AddressBean>) {
        val provinceItems = mutableListOf<AddressInfoPO>()
        val cityItems = mutableListOf<MutableList<AddressInfoPO>>()
        val areaItems = mutableListOf<MutableList<MutableList<AddressInfoPO>>>()
        //Json2Bean
//        val pcaCodeList = Gson().fromJson<MutableList<PCACodePO>>(FileUtil.getAssetsFileText(mApplication, "pcacode.json"), object : TypeToken<MutableList<PCACodePO>>() {}.type)
        //遍历省
        pcaCodeList.forEach { pcaCode ->
            //存放省内市区
            val cityList = mutableListOf<AddressInfoPO>()
            //存放省内所有辖区
            val areaList = mutableListOf<MutableList<AddressInfoPO>>()
            //遍历省内市区
            pcaCode.citys.forEach { cCode ->
                //添加省内市区
                cityList.add(AddressInfoPO(cCode.id, cCode.name))
                //存放市内辖区
                val areas = mutableListOf<AddressInfoPO>()
                //添加市内辖区
                cCode.countys.forEach { addressInfo ->
                    areas.add(AddressInfoPO(addressInfo.id, addressInfo.name))
                }
                areaList.add(areas)
            }
            //添加省份
            provinceItems.add(AddressInfoPO(pcaCode.id, pcaCode.name))
            //添加市区
            cityItems.add(cityList)
            //添加辖区
            areaItems.add(areaList)
        }
        //显示选择器
        showAddressPicker(provinceItems, cityItems, areaItems)
    }


    /**
     * 显示地址选择
     */
    fun showAddressPicker(
        provinceItems: MutableList<AddressInfoPO>,
        cityItems: MutableList<MutableList<AddressInfoPO>>,
        areaItems: MutableList<MutableList<MutableList<AddressInfoPO>>>
    ) {
        //条件选择器
        val pvOptions = OptionsPickerBuilder(this@PersonalInfoActivity,
            OnOptionsSelectListener { options1, option2, options3, v ->
                //返回的分别是三个级别的选中位置
                var tx = ""
                println("####区数据1${areaItems[options1][option2].size}")
                if (areaItems[options1][option2].size < 11) {
                    tx = provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText
                } else {
                    tx =
                        provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText + areaItems[options1][option2][options3].pickerViewText
                }
                tv_area.text = tx//山东省AddressInfoPO(id=2, name=济南2)章丘
                println("####$tx")
                userInfo?.province = provinceItems[options1].pickerViewText
                userInfo?.city = cityItems[options1][option2].pickerViewText
                UserCache.save(userInfo)
                updateUser()
            }).build<AddressInfoPO>()
        pvOptions.setPicker(provinceItems, cityItems, areaItems)
        pvOptions.show()
    }


    private var birthday = ""
    private var headUrl = ""
    lateinit var cal: Calendar
    var year: Int = 0
    var month: Int = 0
    var day: Int = 0
    var hour: Int = 0
    var minute: Int = 0
    private fun dialog() {
        val dateDialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { dp, year, month, dayOfMonth ->
                //2017-12-04 12：00：00
                birthday =
                    year.toString() + "-" + (if (month + 1 < 10) "0" + (month + 1) else month + 1) + "-" + if (dayOfMonth < 10) "0$dayOfMonth" else dayOfMonth
//                age = getCurrentAgeByBirthdate(birthday).toString()
                tv_brithday.text = birthday
                userInfo?.birthday = birthday
                UserCache.save(userInfo)
                updateUser()

            }, year, cal.get(Calendar.MONTH), day
        )
        dateDialog.setTitle("请选择日期")
        dateDialog.show()
    }
    override fun closeMvp() {
    }

}
